package com.xj0927.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;

import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: xj0927
 * @Description:
 * @Date Created in 2020-10-28 11:53
 * @Modified By:
 */
@Component  //让其可以被扫描
public class MyLb implements LoadBalancer {

    //定义原子类：保存请求次数
    private AtomicInteger atomicInteger = new AtomicInteger(0);


    //得到请求次数
    public final int getAndIncrement(){//自旋 + CAS
        int current;
        int next;
        do {
            //得到当前请求次数和需要修改的请求次数
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        }while(!this.atomicInteger.compareAndSet(current,next));
        System.out.println("第几次请求：" + next);
        return next;
    }


    //负载均衡算法：rest 接口第几次请求 % 服务器集群总数量 = 实际调用服务器位置下标，每次服务重启后 rest 接口计数从 1 开始
    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {

        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
